{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Modules for data processing\n",
    "import numpy as np\n",
    "import os\n",
    "from netCDF4 import Dataset\n",
    "import scipy.io as sio\n",
    "import xlrd\n",
    "\n",
    "# Modules for plotting\n",
    "from ipywidgets import *\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "import bokeh.io\n",
    "import bokeh.mpl\n",
    "import bokeh.plotting\n",
    "bokeh.io.output_notebook()\n",
    "import seaborn as sns\n",
    "sns.set_style(style='white')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Option 1: Load data from an Excel file\n",
    "<pre>\n",
    "workbook = xlrd.open_workbook(<span style=\"color:#cc7a00\"><b>'EXCEL_FILE.xlsx'</b></span>)\n",
    "sheet_names = workbook.sheet_names()\n",
    "sheet = workbook.sheet_by_name(sheet_names[i])\n",
    "</pre>\n",
    "\n",
    "#### Option 2: Load data from a Matlab file\n",
    "<pre>\n",
    "matfile  = sio.loadmat(<span style=\"color:#cc7a00\"><b>'MATLAB_FILE.mat'</b></span>)\n",
    "data = matfile[<span style=\"color:#cc7a00\"><b>'VARIABLE_FORCING'</b></span>]\n",
    "</pre>\n",
    "\n",
    "#### Option 3: Load data from a netCDF file\n",
    "<pre>\n",
    "nc_fid = Dataset(<span style=\"color:#cc7a00\"><b>'NETCDF_FILE.nc'</b></span>, 'r')\n",
    "data = nc_fid.variables[<span style=\"color:#cc7a00\"><b>VARIABLE_FORCING</b></span>][:]\n",
    "</pre>\n",
    "\n",
    "#### Run the command below to create forcing for Dhara model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Load matlab file\n",
    "matfile  = sio.loadmat('flux_data.mat')\n",
    "\n",
    "# Load variables\n",
    "doy_in_float = matfile['doy']\n",
    "doy_in       = doy_in_float.astype(int)\n",
    "years_in     = matfile['year']\n",
    "decdoy_in    = matfile['decdoy']\n",
    "Rg_in        = matfile['Rg_in']\n",
    "Pa_in        = matfile['Pa_in']\n",
    "LWdn_in      = matfile['LWdn_in'].T\n",
    "ZEN_in       = matfile['ZEN_in']\n",
    "U_in         = matfile['U_in']\n",
    "PPT_in       = matfile['PPT_in']\n",
    "Ta_in        = matfile['Ta_in']\n",
    "ea_in        = matfile['ea_in']\n",
    "hour_in      = matfile['hour'].T\n",
    "num_steps_in = len(doy_in)\n",
    "\n",
    "# Optional - fill in gap for Longwave using Stefan Boltzmann eqn\n",
    "for i in range(0,num_steps_in):\n",
    "    if np.isnan(LWdn_in[0][i]):\n",
    "        LWdn_in[0][i] = 5.670373e-8 * 0.975 * (Ta_in[i]+273.15)**4\t\n",
    "        \n",
    "# Check/create folder and topography file name\n",
    "folder = 'data'\n",
    "filename_output = '/forcings_' + str(num_steps_in) + '.nc'\n",
    "if not os.path.exists(folder):\n",
    "    os.makedirs(folder)\n",
    "\n",
    "################################################################\n",
    "# DO NOT CHANGE BELOW THIS LINE --------------------------------\n",
    "################################################################\n",
    "\n",
    "forcing = Dataset(folder + '/' + filename_output, 'w', format='NETCDF4')\n",
    "forcing.description = 'Forcing Data for Dhara'\n",
    "\n",
    "# Set up dimension\n",
    "forcing.createDimension('time', num_steps_in)\t# Time series variable\n",
    "forcing.createDimension('scalar', 1)\t\t\t# Scalar variable\n",
    "\n",
    "\"\"\"\n",
    "Create variables in the netcdf file\n",
    "\tvar = netcdf.createVariable('Var_name', 'var_type', ('dimension_type'))\n",
    "\"\"\"\n",
    "doy       = forcing.createVariable('DayOfYear', 'i4', ('time'))\n",
    "years     = forcing.createVariable('Year', 'i4', ('time'))\n",
    "decdoy    = forcing.createVariable('DecimalDayOfYear', 'f8', ('time'))\n",
    "hour      = forcing.createVariable('Hour', 'f8', ('time'))\n",
    "Rg        = forcing.createVariable('GlobalRadiation', 'f8', ('time'))\n",
    "Pa        = forcing.createVariable('AtmosphericPressure', 'f8', ('time'))\n",
    "LWdn      = forcing.createVariable('LongwaveDownward', 'f8', ('time'))\n",
    "ZEN       = forcing.createVariable('ZenithAngle', 'f8', ('time'))\n",
    "U         = forcing.createVariable('WindVelocity', 'f8', ('time'))\n",
    "PPT       = forcing.createVariable('Precipitation', 'f8', ('time'))\n",
    "Ta        = forcing.createVariable('AirTemperature', 'f8', ('time'))\n",
    "ea        = forcing.createVariable('VaporPressureAir', 'f8', ('time'))\n",
    "num_steps = forcing.createVariable('NumTimeSteps', 'i4', ('scalar'))\n",
    "\n",
    "\n",
    "# Assign data to variables in NetCDF file\n",
    "doy[:]       = doy_in\n",
    "years[:]     = years_in\n",
    "decdoy[:]    = decdoy_in\n",
    "Rg[:]        = Rg_in\n",
    "Pa[:]        = Pa_in\n",
    "LWdn[:]      = LWdn_in\n",
    "ZEN[:]       = ZEN_in\n",
    "U[:]         = U_in\n",
    "PPT[:]       = PPT_in\n",
    "Ta[:]        = Ta_in\n",
    "ea[:]        = ea_in\n",
    "hour[:]      = hour_in\n",
    "num_steps[:] = num_steps_in\n",
    "\n",
    "# Close the file\n",
    "forcing.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### If you want to visualize forcing data, run the two commands below"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def plot_forcing(var_name):\n",
    "    nc_fid = Dataset(folder + '/' + filename_output, 'r')\n",
    "    x = nc_fid.variables['DecimalDayOfYear'][:] # common variable on x-axis\n",
    "    var = nc_fid.variables[var_name][:]\n",
    "    \n",
    "    # Plotting data\n",
    "    fig, ax = plt.subplots(figsize=(9,5))\n",
    "    ax.plot(x,var)\n",
    "    ax.set_xlabel('Time (day)')\n",
    "    ax.set_ylabel(var_name)\n",
    "    \n",
    "    # make the plot interactive with Bokeh package\n",
    "    bokeh.plotting.show(bokeh.mpl.to_bokeh())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "var_name = ['AirTemperature',\n",
    "            'GlobalRadiation',\n",
    "            'LongwaveDownward',\n",
    "            'Precipitation',\n",
    "            'VaporPressureAir',\n",
    "            'WindVelocity',\n",
    "            'ZenithAngle',\n",
    "            'AtmosphericPressure']\n",
    "interact(plot_forcing, var_name=var_name)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
